package org.mii.safeguard_v1.security.service.util;

import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Iterator;

import org.apache.commons.beanutils.PropertyUtils;
import org.mii.safeguard_v1.security.web.UserAction;
import org.springframework.util.Assert;
/**
 * 授权工具类
 * @author QUANXIWEI
 */
public class AuthorityUtils {

	/**
	 * 根据传递来的id，更新原有的权限。如果原有权限包含该id，则在原来权限中删除，如果原来权限中没有该id，则添加
	 * 
	 * @author QUANXIWEI
	 */
	public static <T> int updateAuthorites(Collection<T> authList,
			Integer authId, boolean isChecked, String idName, Class<T> clazz)
			throws InstantiationException, IllegalAccessException {

		// 参数校验
		Assert.notNull(authList, "authList不能为空");
		Assert.notNull(clazz, "clazz不能为空");

		try {
			boolean isContainedThisAuth = false;// 标识对象是否包含指定的权限
			Iterator<T> iterator = authList.iterator();
			while (iterator.hasNext()) {
				T element = iterator.next();
				Object id = PropertyUtils.getProperty(element, idName);
				if (id.equals(authId)) {
					isContainedThisAuth = true;
					break;
				}
			}

			if (!isChecked) {// 如果该id是被取消状态的，则遍历该对象是否有该权限，有则删除
				if (isContainedThisAuth) {
					iterator.remove();
				}
				return 0;// 删除一个权限
			}

			else {
				if (!isContainedThisAuth) {
					T obj = clazz.newInstance();
					PropertyUtils.setProperty(obj, idName, authId);
					authList.add(obj);
				}
				return 1;// 添加一个新权限
			}
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

		return isChecked ? 1 : 0;
	}

	public static <T> int updateAuthority(Collection<T> authList,
			Integer authId, boolean isChecked, String idName, Class<T> clazz)
			throws InstantiationException, IllegalAccessException {

		// 参数校验
		Assert.notNull(authList, "authList不能为空");
		Assert.notNull(clazz, "clazz不能为空");

		try {
			boolean isContainedThisAuth = false;// 标识对象是否包含指定的权限
			Iterator<T> iterator = authList.iterator();
			while (iterator.hasNext()) {
				T element = iterator.next();
				Object id = PropertyUtils.getProperty(element, idName);
				if (id.equals(authId)) {
					isContainedThisAuth = true;
				}else{
					iterator.remove();
				}
			}

			if (!isChecked) {// 如果该id是被取消状态的，则遍历该对象是否有该权限，有则删除
				if (isContainedThisAuth) {
					iterator.remove();
				}
				return 0;// 删除一个权限
			}

			else {
				if (!isContainedThisAuth) {
					T obj = clazz.newInstance();
					PropertyUtils.setProperty(obj, idName, authId);
					authList.add(obj);
				}
				return 1;// 添加一个新权限
			}
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

		return isChecked ? 1 : 0;
	}
	
	/**
	 * 绑定已经授权的资源（这里的资源不是指数据库表的Resource 而是通指各级权限）
	 * 
	 * @param <T>：资源泛型类
	 *            可以使Role Authority Resources等
	 * @param <ID>：资源ID
	 * @param srcObjects：资源对象集合
	 * @param bindingIds：已经授权的对象ID集合
	 * @param clazz：资源类型Class
	 * @param idName:资源javabean中的id字段名称
	 *            一般都是id，可能会比较特殊
	 * @param bindPropertyName：要标识该资源为已绑定资源的字段名称
	 * @author QUANXIWEI
	 * @see {@link UserAction#assignRole()}
	 */
	public static <T, ID> void bindingAuthorizedResource(
			final Collection<T> srcObjects, final Collection<ID> bindingIds,
			final Class<T> clazz, final String idName,
			final String bindPropertyName) {

		try {
			for (Iterator<T> iterator = srcObjects.iterator(); iterator
					.hasNext();) {
				T element = (T) iterator.next();
				Object id = PropertyUtils.getProperty(element, idName);
				if (bindingIds.contains(id)) {
					PropertyUtils.setProperty(element, bindPropertyName, 1);
				} else {
					PropertyUtils.setProperty(element, bindPropertyName, 0);
				}
			}
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}
}
